package com.zxl.permission.Interceptor;

import com.alibaba.fastjson.JSONObject;
import com.zxl.permission.controller.NoLogin;
import com.zxl.permission.dao.LoginDao;
import com.zxl.permission.entity.Token;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.Method;
import java.sql.Timestamp;
import java.util.List;


@Component
public class LoginInterceptor implements HandlerInterceptor {
    @Autowired
    LoginDao loginDao;

    private long EXPIRETIME = 1000 * 60 * 60 * 2; // 两个小时token过期

    @Override
    public boolean preHandle(HttpServletRequest req, HttpServletResponse rsp, Object handler) throws Exception {
        // 放通 OPTIONS
        if (req.getMethod().toLowerCase().equals("options")) {
            return true;
        }

        // 放行无需登录的模块
        HandlerMethod handlerMethod = (HandlerMethod) handler;
        Class<?> clazz = handlerMethod.getBeanType();
        Method m = handlerMethod.getMethod();
        if (clazz.isAnnotationPresent(NoLogin.class) || m.isAnnotationPresent(NoLogin.class)) {
            return true;
        }

        // 获取cookie
        Cookie[] cookies = req.getCookies();
        if (cookies == null || cookies.length == 0) {
            rspJson(rsp, 301, "not login");
            return false;   // 无token记录
        }

        // 登录态验证
        boolean find = false;
        for (Cookie cookie : cookies) {
            if (cookie.getName().equals("token")) {
                if ((cookie.getValue().equals(""))) {
                    rspJson(rsp, 301, "not login");
                    return false;   // 无token记录
                }
                List<Token> token = loginDao.getTokenFromToken(cookie.getValue());
                if (token == null) {
                    rspJson(rsp, 301, "not login");
                    return false;   // 无token记录
                }
                Timestamp cur_time = new Timestamp(System.currentTimeMillis());
                if (cur_time.getTime() - token.get(0).active_time.getTime() > EXPIRETIME) {
                    rspJson(rsp, 301, "not login");
                    return false;   // token已过期
                }
                find = true;
                break;
            }
        }
        if (!find) {
            rspJson(rsp, 301, "not login");
            return false;   // 无token记录
        }

        // TODO: 接口访问权限校验
        return true;
    }


    private void rspJson(HttpServletResponse rsp, int code, String msg) {
        JSONObject res = new JSONObject();
        res.put("code", 301);
        res.put("msg", msg);

        rsp.setCharacterEncoding("UTF-8");
        rsp.setContentType("text/plain; charset=utf-8");

        PrintWriter writer = null;
        try {
            writer = rsp.getWriter();
            writer.print(res.toJSONString());
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (writer != null) {
                writer.close();
            }
        }

    }
}
